<?php
namespace ImiApp\Service;

use Imi\Db\Db;
use ImiApp\Model\CityData;
use ImiApp\Enum\CountryType;
use Imi\Bean\Annotation\Bean;
use Imi\Aop\Annotation\Inject;

/**
 * @Bean("CityDataService")
 */
class CityDataService
{
    /**
     * @Inject("AreaDataService")
     *
     * @var \ImiApp\Service\AreaDataService
     */
    protected $areaDataService;

    /**
     * 根据最后修改记录
     *
     * @param string $provinceName
     * @param string $cityName
     * @return \ImiApp\Model\CityData|null
     */
    public function getLastModify(string $provinceName, string $cityName): ?CityData
    {
        return CityData::query()->whereEx([
            'province_name' =>  $provinceName,
            'city_name'     =>  $cityName,
        ])->order('modify_time', 'desc')->limit(1)->select()->get();
    }

    /**
     * 使用数据创建记录
     *
     * @param string $provinceName
     * @param array $data
     * @return \ImiApp\Model\CityData
     */
    public function createByData(string $provinceName, array $data): CityData
    {
        $parent = $this->areaDataService->getByName(CountryType::CHINA, $provinceName);
        if(!$parent)
        {
            throw new \RuntimeException(sprintf('Not found %s', $provinceName));
        }
        $record = CityData::newInstance($data);
        $record->parentId = $parent->id;
        $record->provinceName = $provinceName;
        $record->modifyTime = (int)(microtime(true) * 1000);
        $record->save();
        return $record;
    }

    /**
     * 根据最后修改记录
     *
     * @return \ImiApp\Model\CityData[]
     */
    public function selectLastModify(): array
    {
        static $sql = <<<SQL
SELECT
	* 
FROM
	( SELECT * FROM tb_city_data ORDER BY modify_time DESC ) a 
GROUP BY
    parent_id, city_name
SQL;
        return Db::query()->execute($sql)->getArray();
    }

}
